import Ember from 'ember';

export default Ember.Controller.extend({
  queryCondition:'',
  questionInfo:Ember.Object.create({
    page_errors:Ember.Object.create({}),
  }),
  answerInfo:Ember.Object.create({
    page_errors:Ember.Object.create({}),
  }),

  // sortQuestionList:Ember.computed.sort('questionList',function(a,b){
  //   alert("chainge");
  //   if (a.seq > b.seq) {
  //     return 1;
  //   } else if (a.seq < b.seq) {
  //     return -1;
  //   }
  // }),
  sortObs: function(){
    var sortList = Ember.ArrayProxy.extend({
                    arrangedContent: Ember.computed.sort('content', 'props'),
                    props: ['seq:desc']
                }).create({
                    content: this.get("questionList")});
    this.set("sortQuestionList",sortList);
  }.observes("questionList.@each.seq"),

  seq:Ember.computed('sortQuestionList.@each.seq',function(){
    let seq;
    let firstOne = this.get('sortQuestionList').get('firstObject');
    if(firstOne){
      seq=firstOne.get('seq')+1;

    }else{
      seq=1;
    }
    return seq;
  }),
  services:Ember.computed('curAnswer',function(){
    let curServices = this.get('curAnswer.services');
    let services = new Ember.A();
    curServices.forEach(function(service){
      let ser = Ember.Object.create(service);

      services.pushObject(ser);
    });
    return services;
  }),
  curAnswer:null,
  curQuestion:null,
  detailEdit:false,
  serviceChangeModal:false,
  delEvaModal:false,
  //问卷标题验证
  evaValidate(){
    var evaTitle=this.get('evaInfo.title');
    if(!evaTitle||evaTitle.length===0){
      this.set("evaInfo.page_errors.title","模板标题不能为空");
      this.get("evaInfo").incrementProperty("page_errorsCnt");
      return false;
    }else{
      this.set("evaInfo.page_errors.title",null);
    }
    return true;
  },
  //问题内容和权重验证
  questionValidate(question){
    var questionContent=question.get('content');
    console.log('length:',questionContent.length);
    if(!questionContent||questionContent.length===0){
      this.set('questionInfo.page_errors.content','问题内容不能为空');
      this.get('questionInfo').incrementProperty("page_errorsCnt");
      return false;
    }else{
      this.set("questionInfo.page_errors.content",null);
    }
    return true;
  },
  //答案内容验证
  answerValidate(){
    var answerContent=this.get('answerInfo.content');
    if(!answerContent||answerContent.length===0){
      this.set('answerInfo.page_errors.content','答案内容不能为空');
      this.get('answerInfo').incrementProperty("page_errorsCnt");
      return false;
    }else{
      this.set("answerInfo.page_errors.content",null);
    }
    return true;
  },
  constants: Constants,
  actions:{
    //编辑护理项目
    changeService(){
      console.log(this.get('services'));
      this.set("serviceChangeModal",true);
    },
    //取消按钮
    detailCancel:function(){
      var id=this.get('id');
      var editMode=this.get('editMode');
      if(id&&editMode=='edit'){
        this.set('detailEdit',false);
        this.get('evaInfo').rollbackAttributes();
      }else{
        this.get('evaInfo').rollbackAttributes();
        let mainpageController = App.lookup('controller:business.mainpage');
        mainpageController.switchMainPage('eva-plan');
      }

    },
    //增加新问题
    toAddQuestion(){
      let _self=this;
      let newQuestion=this.store.createRecord('evaluatequestion',{});

      console.log('set seq:',this.get('seq'));
      newQuestion.set('seq',this.get('seq'));
      newQuestion.set('model',this.get('evaInfo'));
      newQuestion.save().then(function(){
        _self.store.query('evaluatequestion',{sort:{seq:'desc'},filter:{model:{id:_self.get('evaInfo.id')}}}).then(function(questionList){
          _self.set('questionList',questionList);
        });

        _self.send('chooseQuestion',newQuestion);
        _self.store.query('Evaluateanswer',{filter:{question:{id:_self.get('curQuestion.id')}}}).then(function(answerList){
          _self.set('answerList',answerList);

        });
      });
    },
    //增加新答案
    toAddAnswer(){
      let _self=this;
      let newAnswer=this.store.createRecord('evaluateanswer',{});
      newAnswer.set('question',this.get('curQuestion'));
      newAnswer.save().then(function(){
        _self.store.query('Evaluateanswer',{filter:{question:{id:_self.get('curQuestion.id')}}}).then(function(answerList){
          _self.set('answerList',answerList);
        });
      });
    },
    //弹窗取消按钮
    invitation(){
      console.log('services:',this.get('services'));
      this.set("curAnswer.services",this.get('services'));
      this.set("serviceChangeModal",false);
      this.set("delEvaModel",false);
    },
    //保存新问题
    saveNewQuestion(question){
      var _self=this;
      if(this.questionValidate(question)){
        question.save().then(function(){
          _self.store.query('evaluatequestion',{sort:{id:'desc'},filter:{model:{id:_self.get('evaInfo.id')}}}).then(function(questionList){
            _self.set('questionList',questionList);
          });

        });
      }


    },
    //保存服务项目
    saveNewService(){
      var _self=this;
      var curAnswerServices=new Ember.A();

      this.get('curAnswer').save().then(function(){
        _self.set("serviceChangeModal",false);
      });
    },
    //保存新答案
    saveNewAnswer(){
      var _self=this;
      var newAnswer=this.store.createRecord('evaluateanswer',{});
      newAnswer.set('content',this.get('answerInfo.content'));
      if(this.get('answerInfo.score')){
        newAnswer.set('score',this.get('answerInfo.score'));
      }
      if(this.get('answerInfo.services')){
        newAnswer.set('services',this.get('answerInfo,services'));
      }
      newAnswer.set('question',this.get('curQuestion'));
      if(this.answerValidate()){
        newAnswer.save().then(function(){
          _self.set('answerSaveModel',false);
          _self.send('chooseQuestion');
        });
      }

    },
    //编辑按钮
    detailEditClick:function(){
      this.set('detailEdit',true);
    },
    //选择问题
    chooseQuestion(question,index){
      let name='input'+index;
      this.set("answerList",null);
      var _self = this;
      var curQuestion = this.get("curQuestion");
      //重置原来的选择项
      if(curQuestion&&curQuestion.get("id")){
        console.log('in if now workOrderbefore exist');
        curQuestion.set("hasSelected",false);
      }
      //设置新的选择项
      if(question&&question.get("id")){
        question.set("hasSelected",true);
        this.set("curQuestion",question);
      }
      this.store.query('Evaluateanswer',{filter:{question:{id:this.get('curQuestion.id')}}}).then(function(answerList){
        _self.set('answerList',answerList);

      });
    },
    //提升顺序
    upOrder(question,index){
      var _self=this;
      if(index>0){
        let lastQue=this.get('sortQuestionList').objectAt(index-1);
        let lastSeq=lastQue.get('seq');
        let curSeq=question.get('seq');
        question.set('seq',lastSeq);
        lastQue.set('seq',curSeq);
        console.log("upOrder in，lastSeq:" + lastSeq + " and curSeq:" + curSeq);
        question.save();
        lastQue.save();
        index=index-1;
      }
    },
    //保存问题内容
    saveQuestion(content,type){
      this.get('curQuestion').save().then(function(){
      });
    },
    //保存答案內容
    saveAnswer(content,type){
      this.get('curAnswer').save().then(function(){
      });
    },
    //删除当前问卷弹框
    delPlan(eva){
      var _self = this;
      App.lookup('controller:business.mainpage').showConfirm("是否确定删除此模板记录",function(){
        _self.send('cancelPassSubmit',_self.get('evaInfo'));
      });
    },
    //删除问卷
    cancelPassSubmit(eva){
      App.lookup('controller:business.mainpage').openPopTip("正在删除");
			this.set("delEvaModal",false);
      eva.set("delStatus", 1);
      eva.save().then(function() {
          App.lookup('controller:business.mainpage').showPopTip("删除成功");
          var mainpageController = App.lookup('controller:business.mainpage');
          mainpageController.switchMainPage('eva-plan');

      });
		},
    //删除当前答案
    delAnswer(answer){
      var _self=this;
      App.lookup('controller:business.mainpage').showConfirm("是否确定删除此答案",function(){
        App.lookup('controller:business.mainpage').openPopTip("正在删除");
        answer.set('delStatus',1);
        answer.save().then(function(){
            App.lookup('controller:business.mainpage').showPopTip("删除成功");
          _self.store.query('Evaluateanswer',{filter:{question:{id:_self.get('curQuestion.id')}}}).then(function(answerList){
            _self.set('answerList',answerList);
          });
        });
      });

    },
    //删除当前问题
    delQuestion(question){
      var _self=this;
      App.lookup('controller:business.mainpage').showConfirm("是否确定删除此问题",function(){
        App.lookup('controller:business.mainpage').openPopTip("正在删除");
        question.set('delStatus',1);
        question.set('seq',null);
        question.save().then(function(){
          App.lookup('controller:business.mainpage').showPopTip("删除成功");
          _self.store.query('evaluatequestion',{sort:{seq:'desc'},filter:{model:{id:_self.get('evaInfo.id')}}}).then(function(questionList){
            _self.set('questionList',questionList);
          });
          _self.set('curQuestion','');
        });
      });

    },
    invalid() {
        //alert("error");
    },
    //保存问卷信息
    savePlan(){

      var editMode=this.get('editMode');
      var evaInfo=this.get('evaInfo');
      evaInfo.set('type',this.get('evaInfo.type'));
      var _self=this;
      if(this.evaValidate()){
        App.lookup('controller:business.mainpage').openPopTip("正在保存");
        if(editMode=='add'){
          evaInfo.set('delStatus',0);
          evaInfo.save().then(function(){
            App.lookup('controller:business.mainpage').showPopTip("保存成功");
            var mainpageController = App.lookup('controller:business.mainpage');
            mainpageController.switchMainPage('eva-plan');
          });
        }else{
          evaInfo.save().then(function(){
              App.lookup('controller:business.mainpage').showPopTip("保存成功");
              _self.set('detailEdit',false);
          });
        }
      }
    },
    //选择答案
    selectAnswer(answer){
      var _self=this;
      var curAnswer = this.get("curAnswer");
      if(curAnswer&&curAnswer.get("id")){
        curAnswer.set("hasSelected",false);
      }
      //设置新的选择项
      if(answer&&answer.get("id")){
        answer.set("hasSelected",true);
        _self.set("curAnswer",answer);
      }
    },
    //选择评估方式
    evaluateTypeSelect(evaluateType){
      var _self=this;
      this.set('evaInfo.evaluateType',evaluateType);
      if(evaluateType.get('typename')=='分数评测'){
        _self.set('score',true);
      }
      if(evaluateType.get('typename')=='护理项目评测'){
        _self.set('score',false);
      }
    },
    //搜索
    search(){
      var _self=this;
      this.store.query('evaluatequestion',{filter:{model:{id:this.get('evaInfo.id')},'content@$like':this.get('queryCondition')}}).then(function(questionList){
        _self.set('questionList',questionList);
      });
    }
  }
});
